from awvs.base import Base
from lib.cache import file_cache
from lib import parse_fields
from typing import Union


class Vulnerabilities(Base):
    @property
    def __vulnerabilities_property(self):
        return [
            'affects_url',
            'confidence',
            'severity',
            'status',
            'tags',
            'cvss3',
            'cvss_score',
            'description',
            'request',
        ]

    @property
    def vulnerabilities(self) -> list:
        api = f'{self.url}/vulnerabilities'
        r = self.session.get(api)
        if r.status_code == 200:
            result = self.scroll_pages(r, api, 'vulnerabilities')
            return result
        else:
            print(' No vulnerabilities found')
            return []

    def get_vuln(self, target_id, severity: Union[int, str] = '2,3') -> list:
        api = f'{self.url}/vulnerabilities'
        r = self.session.get(
            api+f'?q=severity:{severity};target_id:{target_id};')
        result = self.scroll_pages(
            r, api, 'vulnerabilities', params=f'q=severity:{severity};target_id:{target_id};')
        return result

    def export_vulns(self, target_id: str):
        vulns = self.get_vuln(target_id)
        if not vulns:
            return
        for vuln in vulns:
            vuln_id = vuln['vuln_id']
            vuln.update(self.get_vulnerabilities_details(vuln_id))
        vulns = parse_fields(vulns, self.__vulnerabilities_property)
        return vulns

    @file_cache()
    def get_vulnerabilities_details(self, vuln_id) -> dict:
        api = f'{self.url}/vulnerabilities/{vuln_id}'
        r = self.session.get(api)
        if r.status_code == 200:
            return r.json()
        else:
            print(f'{vuln_id} vulnerabilities has no found')
            return {}

    @file_cache()
    def get_vulnerability_http_response(self, vuln_id) -> bytes:
        api = f'{self.url}/vulnerabilities/{vuln_id}/http_response'
        r = self.session.get(api)
        if r.status_code == 200:
            return r.content
        else:
            print(f'{vuln_id} vulnerability http_response has no found')
            return b''
